using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace UpdaterForm
{
    //TODO: posle togo kak  smogu ispolzovat class Update vmesto Update Info, pomenat nazvanie classa na Info
    public class UpdateData
    {
        public string Name { get; set; }
        public long Size { get; set; }
        public string SizeFormed { get; set; }
        public int Lenght { get; set; }
        public string Message { get; set; }
        public string FullName { get; set; }


        public UpdateData(DirectoryInfo dir)
        {
            if (dir.Parent != null)
                Name = dir.Parent.Name;
            FullName = dir.FullName;
            Message = ReadUpdateMessage();
            Lenght = dir.GetFiles("*", SearchOption.AllDirectories).Length; 
            Size = DirSize(dir);
            SizeFormed = ToBytes(Size);
        }

        private string ReadUpdateMessage()
        {
            try
            {
                var fileName = Path.Combine(FullName, Settings.Instance.MessageFileName);
                return File.ReadAllText(fileName);

            }
            catch (Exception)
            {
                return String.Empty;
            }
        }

        private static string ToBytes(long bytes)
        {
            IList<string> units = new List<string> { "B", "KB", "MB", "GB", "TB" };
            var pow = Math.Floor((bytes > 0 ? Math.Log(bytes) : 0) / Math.Log(1024));
            pow = Math.Min(pow, units.Count - 1);
            var value = bytes / Math.Pow(1024, pow);
            return value.ToString(pow == 0 ? "F0" : "F" + 2) + " " + units[(int)pow];
        }

        private static long DirSize(DirectoryInfo d)
        {
            var fis = d.GetFiles();
            var Size = fis.Sum(fi => fi.Length);
            var dis = d.GetDirectories();
            Size += dis.Sum(di => DirSize(di));
            return (Size);
        }
    }
}